<?php
   // Import the constants file. This imports DATABASEADDRESS, DATABASEUSER, DATABASEPASS, and DATABASENAME
   require("constants.php");
   // Import the functions file. This importants the database_down() function
   require("functions.php");

	// Check to see if the question type and the question were sent successfully
	if (isset($_POST["question_type"]) && isset($_POST["question"]))
	{
		$answer_count = 0; // Loop variable to detect the amount of answers sent to the page

		// Loop through, checking if answer_(answer_count) has been sent.
		do
		{
			$answer_count++;
		} while (isset($_POST['answer_' + $answer_count]);
	}

	// Insert the question into the database
   $database = mysqli_connect(DATABASEADDRESS,DATABASEUSER,DATABASEPASS);

   if (mysqli_connect_errno())
   {
      database_down();
   }
     
   @ $database->select_db(DATABASENAME) or database_down();
   
   $query = "INSERT INTO questions (question_type, question) VALUES (?, ?);";

   $statement = $database->prepare($query);

   $statement->bind_param("ss", $_POST['question_type'], $_POST['question']);

   $statement->execute();  

   mysqli_close($database);

   // TO DO: Declare and receive the question_id

   // Insert the answers into the database one at a time
   for ($count = 1; $count <= $answer_count; $count++)
   {
	   $database = mysqli_connect(DATABASEADDRESS,DATABASEUSER,DATABASEPASS);

	   if (mysqli_connect_errno())
	   {
	      database_down();
	   }
	     
	   @ $database->select_db(DATABASENAME) or database_down();
	   
	   $query = "INSERT INTO answers (question_id, answer, is_correct) VALUES (?, ?, ?);";

	   $statement = $database->prepare($query);

	   $statement->bind_param("sss", $question_id, $_POST['answer_' + $count], $_POST['answer_' + $count + 'is_correct']);

	   $statement->execute();  

	   mysqli_close($database);
   }
?>